import { get, isEqual } from 'lodash-es'

import type { SortableEvent } from '..'
import type { CascaderDiff, CascaderDiffData, CascaderDiffSource, Data } from '../types/cascader'

const regionsMap = ref<Data>({})
const nodesMap = ref<Data>({})
const diffObj = ref<Data<CascaderDiff>>({})

const risk = ref<Data>()

export const useCascaderStore = () => {
  const getDiffType = (from: CascaderDiffSource, to: CascaderDiffSource) => {
    // 判断是否发生区域变更
    const regionChanged = from.region !== to.region
    // 判断是否发生层级变更
    const levelChanged = from.level !== to.level

    const diffType = levelChanged ? (regionChanged ? 'REGION_LEVEL' : 'LEVEL') : regionChanged ? 'REGION' : 'SORT'

    return diffType
  }

  const setDiffData = (data: CascaderDiffData, evt?: SortableEvent) => {
    const { to, node } = data
    const { source } = get(nodesMap.value, node)
    // 如果 diff中存在当前节点

    const diffData: CascaderDiff = {
      diffType: getDiffType(source, to),
      source,
      ...data
    }

    // 防止只有一个节点时 从L1 拖动到 L2  再从 L2拖动到L1 空提示占索引触发的bug
    if (diffData.diffType === 'SORT' && evt?.to?.children?.length === 1) {
      diffData.to.index = 0
      // 重新计算一次 diffType
      diffData.diffType = getDiffType(source, diffData.to)
    }

    if (isEqual(source, to)) {
      delete diffObj.value[node]
    } else {
      diffObj.value[node] = diffData
    }
  }

  const resetDiff = () => (diffObj.value = {})

  const diff = computed<CascaderDiff[]>(() => Object.values(diffObj.value))

  return { regionsMap, nodesMap, diff, setDiffData, risk, resetDiff }
}
